package com.link.base.base.share.controller;

import com.link.base.base.activity.model.ActivityConfig;
import com.link.base.base.activity.model.ActivityResult;
import com.link.base.base.activity.model.CorpActivity;
import com.link.base.base.activity.service.ActivityConfigService;
import com.link.base.base.activity.service.ActivityResultService;
import com.link.base.base.activity.service.CorpActivityService;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.service.BasicService;
import com.link.core.cllog.LCLogger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 组织活动控制器
 * @author unknown
 * @date unknown
 */
@Controller
@RequestMapping("/link/share")
public class ShareActivityController extends BasicController<CorpActivity> {
    @Resource
    private CorpActivityService corpActivityService;
    @Resource
    private ActivityConfigService activityConfigService;
    @Resource
    private ActivityResultService activityResultService;

    @Override
    public BasicService<CorpActivity> getBasicService() throws Exception {
        return corpActivityService;
    }

    /**
     * 保存活动数据
     * @author 郭闪
     * @date 2019/12/26
     * @param session
     * @param request
     * @param response
     *
     */
    @RequestMapping(value = "/submitdata", method = RequestMethod.POST)
    @ResponseBody
    public void submitdata(HttpSession session, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        //获取请求参数
        String sessionId = request.getSession().getId();
        String rowid = request.getParameter("rowid");
        String agent = request.getHeader("user-agent");
        String clientType = "";
        String micromessenger = "micromessenger";
        String iphone = "iphone";
        String ipad = "ipad";
        String android = "android";

        //设置客户端类型
        if (agent.indexOf(micromessenger) != -1) {
            clientType = "微信";
        } else if (agent.indexOf(iphone) != -1) {
            clientType = "iphone";
        } else if (agent.indexOf(ipad) != -1) {
            clientType = "ipad";
        } else if (agent.indexOf(android) != -1) {
            clientType = "android";
        } else {
            clientType = "web";
        }

        List<ActivityResult> results = new ArrayList<ActivityResult>();
        //根据活动ID查询此活动下的活动配置
        ActivityConfig ac = new ActivityConfig();
        ac.setParentId(Long.parseLong(rowid));
        List<ActivityConfig> lines = (List<ActivityConfig>) activityConfigService.queryAll(ac);
        String msg = "";

        //校验请求参数中是否缺少必输的参数，并将活动结果添加到list中
        for (ActivityConfig line : lines) {
            String pName = line.getDisplayName();
            String isReq = line.getIsReq();
            String val = "";
            try {
                //获取某个displayName 对应的所有值
                String[] arr = request.getParameterValues(pName);
                for (int i = 0; i < arr.length; i++) {
                    val += arr[i];
                    if (i > 1) {
                        val += ",";
                    }
                }
            } catch (Exception e) {
                LCLogger.withException(e);
            }
            //判断此displayName是否为必输，且是否有值
            if ("Y".equals(isReq) && "".equals(val)) {
                msg += pName + "为必输信息，请完善！";
                continue;
            }
            //设置活动结果信息
            ActivityResult r1 = new ActivityResult();
            r1.setSessionId(sessionId);
            r1.setParentId(Long.parseLong(rowid));
            r1.setReqType(clientType);
            String seq = line.getSeq();
            r1.setSeq(seq);
            r1.setName(pName);
            r1.setValue(val);
            results.add(r1);
        }
        //判断是否有错误信息
        if ("".equals(msg)) {
            ActivityResult r = new ActivityResult();
            r.setSessionId(sessionId);
            r.setParentId(Long.parseLong(rowid));

            //保存所有的活动结果
            for (ActivityResult r1 : results) {
                try {
                    activityResultService.insert(r1);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    LCLogger.withException(e);
                }
            }
        }

        //拼接HTML，返回结果
        StringBuffer str = new StringBuffer();
        str.append(
                "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>");
        str.append("<html xmlns='http://www.w3.org/1999/xhtml'>");
        str.append(
                "<head><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><meta name=\"viewport\" content=\"width=device-width,"
                        + " initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes\" />");
        str.append("<link rel=\"stylesheet\" href=\"/static/css/shareActivityPublic.css\">");
        str.append("<title>提交成功</title></head><body>");
        if ("".equals(msg)) {
            str.append("<body>提交成功!</body></html>");
        } else {
            str.append("<body>" + msg + "</body></html>");
        }
        try {
            response.getWriter().write(str.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            LCLogger.withException(e);
        }
    }

    /**
     * 返回活动预览信息
     * @date 2019/12/26
     * @param record
     * @param session
     * @param request
     * @param response
     *
     */
    @RequestMapping(value = "/preViewPage", method = RequestMethod.GET)
    @ResponseBody
    public void preViewPage(CorpActivity record, HttpSession session, HttpServletRequest request,
                            HttpServletResponse response) {

        /**
         * 根据活动ID获取活动相关信息，并将信息拼接成HTML格式，返回给签到
         */
        StringBuffer str = new StringBuffer();
        str.append(
                "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>");
        str.append("<html xmlns='http://www.w3.org/1999/xhtml'>");
        str.append(
                "<head><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><meta name=\"viewport\" content=\"width=device-width,"
                        + " initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes\" />");
        str.append("<link rel=\"stylesheet\" href=\"/static/css/shareActivityPublic.css\">");
        try {
            CorpActivity header = (CorpActivity) corpActivityService.queryById(record);
            str.append("<title>" + header.getActivityName() + "</title></head><body>");
            str.append(
                    "<div style='height:80px;text-align: center;margin-top:10px;'> "
                            + "<img src='/static/images/shareActivitylogo.png' style='height:60px'/>");
            str.append("</div><div style='text-align: center;margin-top:10px'> <span class='headertitle'>"
                    + header.getActivityName()
                    + "</span></div><div style='height:auto;'> <form action='/action/portal/share/submitdata' method='POST'>");
            ActivityConfig qps = new ActivityConfig();
            qps.setParentId(record.getId());
            str.append("<input type='hidden' name='rowid' value='" + record.getId() + "'>");
            List<ActivityConfig> lines = (List<ActivityConfig>) activityConfigService.queryAll(qps);
            for (ActivityConfig line : lines) {
                String InputType = line.getInputType();
                String isReq = line.getIsReq();
                String txt = line.getSelectRange();
                String tmp = "";
                if ("输入".equals(InputType)) {
                    tmp = "<div class='div inputdiv'>"
                            + "<div class='item3'>[title]</div><div class='item4'><input type='text' class='input_text' name='[title]'>";
                    if ("Y".equals(isReq)) {
                        tmp += "<span class='tip'>*必输项</span>";
                    }
                    tmp += "</div></div>";
                    tmp = tmp.replace("[title]", line.getDisplayName());
                } else if ("单选".equals(InputType)) {
                    tmp = " <div class='div singselectdiv singselectdiv_[count]'><span class='mytitle'>[title]</span>";
                    if ("Y".equals(isReq)) {
                        tmp += "<span class='tip'>*必输项</span>";
                    }
                    tmp += "<div style='padding:10px'>";
                    String[] sourceStrArray = txt.split(",");
                    for (int i = 0; i < sourceStrArray.length; i++) {
                        tmp += "<div class='select' ><input type='radio' name='[title]' value='" + sourceStrArray[i]
                                + "'/>" + sourceStrArray[i] + " </div>";
                    }
                    tmp += "</div></div>";
                    tmp = tmp.replace("[title]", line.getDisplayName());
                    int a = sourceStrArray.length;
                    tmp = tmp.replace("[count]", String.valueOf(a));
                } else if ("多选".equals(InputType)) {
                    tmp = " <div class='div mulselectdiv mulselectdiv_[count]'><span class='mytitle'>[title]</span>";
                    if ("Y".equals(isReq)) {
                        tmp += "<span class='tip'>*</span>";
                    }
                    tmp += "<div style='padding:10px'>";
                    String[] sourceStrArray = txt.split(",");
                    for (int i = 0; i < sourceStrArray.length; i++) {
                        tmp += "<div class='select' ><input type='checkbox' name='[title]' value='" + sourceStrArray[i]
                                + "'/>" + sourceStrArray[i] + " </div>";
                    }
                    int a = sourceStrArray.length;
                    tmp = tmp.replace("[count]", String.valueOf(a));
                    tmp += "</div></div>";
                    tmp = tmp.replace("[title]", line.getDisplayName());
                } else if ("备注".equals(InputType)) {
                    tmp = "<div class='div comsinputdiv'><span class='mytitle'>[title]</span>";
                    if ("Y".equals(isReq)) {
                        tmp += "<span class='tip'>*</span>";
                    }
                    tmp += "<div style='margin-top:10px;text-align: center'>";
                    tmp += "<textarea name ='[title]' class='textarea' placeholder='请输入[title]' rows='3'></textarea></div> </div>";
                    tmp = tmp.replace("[title]", line.getDisplayName());
                }
                str.append(tmp);
            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        str.append("<input class='submitbtn' type=\"submit\" value=\"提交\"/></form></div></body></html>");
        try {
            response.getWriter().write(str.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            LCLogger.withException(e);
        }
    }
}
